//
//  UserDetailViewController.m
//  DaJiang
//
//  Created by sally on 16/10/5.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CellManager.h"
#import "UserDetailViewController.h"
#import "DemoImageEditor.h"
#import "MainModel.h"
#import "PickerView.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface UserDetailViewController () <UITextViewDelegate,UIPickerViewDelegate, UIPickerViewDataSource,PickerViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *bgImage;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;

@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) UIImageView *headImage;
@property (strong, nonatomic) UITextField *nameTextField;
@property (strong, nonatomic) UITextField *locTextField;
@property (strong, nonatomic) UITextField *titleTextField;
@property (strong, nonatomic) UITextField *indexTextField;
@property (strong, nonatomic) UITextField *index2TextField;
@property (strong, nonatomic) NSString *userName;
@property (strong, nonatomic) NSString *loc;
@property (strong, nonatomic) NSString *titleStr;
@property (strong, nonatomic) NSString *indexStr;
@property (strong, nonatomic) NSString *index2Str;
@property (strong, nonatomic) NSString *desc;
@property (assign, nonatomic) BOOL isHeadImage;//是否是选择的头像，而非背景头图
@property (strong, nonatomic) UIImage *headSetImage;//新选择的头像
@property(nonatomic,strong) DemoImageEditor *imageEditor;
@property(nonatomic,strong) ALAssetsLibrary *library;
@property (strong, nonatomic) NSMutableArray *locArr;
@property (strong, nonatomic) PickerView *locPicker;  //地区选择器

@end

@implementation UserDetailViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
  [self loadData];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark 设置通知
- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = @"个人资料";
  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(save)];
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
  
  if (self.userType == UserDetailType_Expert) {
    self.headerView.height = GExpertImageHeight;
    [self.bgImage sd_setImageWithURL:[NSURL URLWithString:self.userModel.user_data.user_profile_bg_pic] placeholderImage:[UIImage imageNamed:@"large_image_default"]];
  } else {
    self.headerView.height = 0;
    self.changeBtn.hidden = YES;
  }
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.locArr = [[NSMutableArray alloc] init];
  [self.tableData addObject:@[ @"头像", @"昵称", @"所在地" ]];
  if (self.userType == UserDetailType_Expert) {
    [self.tableData addObject:@[ @"专业名称", @"专业分类", @"专业分类2" ]];
    [self.tableData addObject:@[ @"个人介绍", @"" ]];
  }
  [self initControlText];
  
  //从plist中获取地区列表的缓存数据
  NSMutableArray *arr1 = [[CacheManager shareInstance] getLocArr];
  self.locArr = [[NSMutableArray alloc] initWithArray:arr1];
}

- (void)loadData {
  //加载地区列表数据
  [LocationModel queryLocationListWithCompletion:^(NSMutableArray *locList) {
    if (locList) {
      [[CacheManager shareInstance] cacheLocArr:locList];
      [self.locArr removeAllObjects];
      self.locArr = locList;
    } else {
      NSError *error = [LocationModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

#pragma mark 初始化控件数据
- (void)initControlText {
  self.userName = self.userModel.user_data.user_name;
  self.loc = self.userModel.user_data.user_location_name;
  self.titleStr = self.userModel.user_data.user_pro_title;
  self.indexStr = self.userModel.user_data.user_pro_topic_index;
  self.index2Str = self.userModel.user_data.user_pro_topic_index2;
  self.desc = self.userModel.user_data.user_pro_desc;
}

#pragma mark - aciton
#pragma mark 更换头图
- (IBAction)actionOnChange:(id)sender {
  self.isHeadImage = NO;
  [OperationManager configCameraActionSheet];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.tableData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [[self.tableData objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 0.1; //section头部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return GNormalMargin; //section底部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 0 && indexPath.row == 0) { //第一行
    return GMineHeadCellHeight;
  } else if (indexPath.section == 2 && indexPath.row == 1) { //最后一项
    return GTextViewHeight - NavHeight;
  }
  return NavHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  UITableViewCell *cell;
  if (indexPath.section == 0 && indexPath.row == 2 && ![self.loc isEqualToString:@"其他"]) {
    //主副标题形式
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    
    //副标题
    [CellManager configCellDetailText:cell];
    cell.detailTextLabel.text = self.loc ? self.loc : @"";
    
  }else{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //头像
    if (indexPath.section == 0 && indexPath.row == 0) { //第一行
      self.headImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth - GNormalMargin - GHeadImageHeight, GNormalMargin, GHeadImageHeight, GHeadImageHeight)];
      if (self.headSetImage) {
        [self.headImage setImage:self.headSetImage];
      }else{
        [self.headImage sd_setImageWithURL:[NSURL URLWithString:self.userModel.user_data.user_profile_pic] placeholderImage:[UIImage imageNamed:@"ic_default"]];
      }
      self.headImage.layer.cornerRadius = GHeadImageHeight / 2;
      self.headImage.layer.masksToBounds = YES;
      self.headImage.userInteractionEnabled = YES;
      UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeHeadImage)];
      [self.headImage addGestureRecognizer:tap];
      [cell.contentView addSubview:self.headImage];
    }
    
    //编辑行
    else if (indexPath.section == 0 && indexPath.row == 1) {
      self.nameTextField = [CellManager configCellNormalTextField:cell];
      self.nameTextField.text = self.userName;
      [cell.contentView addSubview:self.nameTextField];
    } else if (indexPath.section == 0 && indexPath.row == 2) {
      self.locTextField = [CellManager configCellNormalTextField:cell];
      self.locTextField.text = self.loc;
      [cell.contentView addSubview:self.locTextField];
    } else if (indexPath.section == 1 && indexPath.row == 0) {
      self.titleTextField = [CellManager configCellNormalTextField:cell];
      self.titleTextField.text = self.titleStr;
      [cell.contentView addSubview:self.titleTextField];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
      self.indexTextField = [CellManager configCellNormalTextField:cell];
      self.indexTextField.text = self.indexStr;
      [cell.contentView addSubview:self.indexTextField];
    } else if (indexPath.section == 1 && indexPath.row == 2) {
      self.index2TextField = [CellManager configCellNormalTextField:cell];
      self.index2TextField.text = self.index2Str;
      [cell.contentView addSubview:self.index2TextField];
    }
    
    //编辑框
    else if (indexPath.section == 2 && indexPath.row == 1) { //最后一项
      UITextView *textView = [CellManager configCellTextView:cell];
      textView.text = self.desc;
      textView.delegate = self;
      [cell.contentView addSubview:textView];
    }
    
  }
  
  //主标题
  [CellManager configCellNormalText:cell];
  cell.textLabel.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

  return cell;
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  
  if (indexPath.section == 0 && indexPath.row == 2) {
    self.locPicker = [[PickerView alloc] initWithPickerType:PickerType_Loc];
    self.locPicker.delegate = self;
    [self.locPicker show];
    
    //重载cell
    LocationModel *locModel = self.locArr[0];
    self.loc = locModel.data.pro_user_location_name;
    [self reloadLocCell];
  }
}

#pragma mark Picker Data Source Method
// 返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  return 1;
}

// 返回该列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  return self.locArr.count;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
  LocationModel *loc = [self.locArr objectAtIndex:row];
  self.loc = loc.data.pro_user_location_name;
  
  //重载cell
  [self reloadLocCell];
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  LocationModel *loc = [self.locArr objectAtIndex:row];
  return loc.data.pro_user_location_name;
}

#pragma mark PickerViewDelegate
- (void)cancelSelect:(UIView *)picker{
  if (picker == self.locPicker){
    self.loc = self.userModel.user_data.user_location_name;
    [self reloadLocCell];
  }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  NSString *selectStr = [actionSheet buttonTitleAtIndex:buttonIndex];
  UIImagePickerController *imagePicker = [OperationManager configImagePicker:selectStr];
  //背景头图也需要截取,尺寸：GExpertImageHeight*屏幕宽
  if (imagePicker) {
    if (self.isHeadImage) {
      imagePicker.allowsEditing = YES;
    }else{
      ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
      self.imageEditor = [[DemoImageEditor alloc] initWithNibName:@"DemoImageEditor" bundle:nil];
      self.imageEditor.checkBounds = YES;
      self.imageEditor.rotateEnabled = YES;
      self.library = library;
      
      self.imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
        if(!canceled) {
          editedImage = [[CommonMethod sharedCommonMethod] compressImage:editedImage]; //压缩图片
          [self.bgImage setImage:editedImage];
        }
        if (imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
          [self.navigationController popViewControllerAnimated:NO];
          [self.navigationController setNavigationBarHidden:NO animated:YES];
        }else{
          [self.imageEditor dismissViewControllerAnimated:YES completion:nil];
          [imagePicker dismissViewControllerAnimated:YES completion:nil];
        }
        
      };
    }
  }else{
    return;
  }
}

#pragma mark UIImagePickerControllerDelegate 选照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
  
  //两种情况：头像、背景头图
  if (self.isHeadImage) {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerEditedImage];
    originalImage = [[CommonMethod sharedCommonMethod] compressImage:originalImage]; //压缩图片
    self.headSetImage = originalImage;
  }else{
    
    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    [self.library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
      UIImage *preview = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
      
      self.imageEditor.sourceImage = image;
      self.imageEditor.previewImage = preview;
      [self.imageEditor reset:NO];
      if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [picker dismissViewControllerAnimated:NO completion:nil];
        [self.navigationController pushViewController:self.imageEditor animated:NO];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
      }else{
        [picker presentViewController:self.imageEditor animated:YES completion:nil];
      }
      
    } failureBlock:^(NSError *error) {
      NSLog(@"Failed to get asset from library");
    }];

  }
  
  [self.tableView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
  self.desc = textView.text;
}

#pragma mark - 私有方法
#pragma mark textfield中的文本发生改变时
- (void)textFieldChanged:(NSNotification *)notification {
  UITextField *textField = (UITextField *)notification.object;
  if ([textField isEqual:self.nameTextField]) {
    self.userName = textField.text;
  }else if ([textField isEqual:self.locTextField]){
    self.loc = textField.text;
  }else if ([textField isEqual:self.titleTextField]){
    self.titleStr = textField.text;
  }else if ([textField isEqual:self.indexTextField]){
    self.indexStr = textField.text;
  }else if ([textField isEqual:self.index2TextField]){
    self.index2Str = textField.text;
  }
}

#pragma mark 保存
- (void)save {
  if (self.loc.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填写所在地呦！"];
    return;
  }
  //上传头像
  [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  [PicModel uploadPicWithImage:self.headImage.image completion:^(PicModel *pic) {
    if (pic) {
      NSString *headPicUrl = pic.original_pic;
      
      if (self.userType == UserDetailType_Expert) {
        //上传头图背景
        [PicModel uploadPicWithImage:self.bgImage.image completion:^(PicModel *pic) {
          if (pic) {
            NSString *bgPicUrl = pic.original_pic;
            
            //完善用户资料
            [self updateUserInfo:headPicUrl bgPicUrl:bgPicUrl];
          } else {
            NSError *error = [PicModel getLastError];
            [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
          }
        }];
      }else{
        //完善用户资料
        [self updateUserInfo:headPicUrl bgPicUrl:@""];
      }
      
    } else {
      NSError *error = [PicModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

#pragma mark 更新用户信息
- (void)updateUserInfo:(NSString *)headPicUrl bgPicUrl:(NSString *)bgPicUrl {
  
  [UserModel updateUserInfoWithUserName:self.userName userProfilePic:headPicUrl locationName:self.loc bigPic:bgPicUrl proDesc:self.desc proTitle:self.titleStr topicIndex:self.indexStr topicIndex2:self.index2Str completion:^(UserModel *user) {
    if (user) {
      UIWindow *window = [UIApplication sharedApplication].keyWindow;
      [[CommonMethod sharedCommonMethod] showToastInCenter:window withMessage:@"已修改用户信息"];
      //缓存用户信息
      [[CacheManager shareInstance] cacheLastLoginAccount:user];
      //退出
      [self.navigationController popViewControllerAnimated:YES];

    } else {
      NSError *error = [UserModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  }];
}

#pragma mark 切换头像
- (void)changeHeadImage {
  self.isHeadImage = YES;
  [OperationManager configCameraActionSheet];
}

#pragma mark 重载地区cell
- (void)reloadLocCell {
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
  [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}

@end
